import 'dart:convert';
import 'dart:io';

import 'package:desktop_multi_window/desktop_multi_window.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:pc/Page/Other/Setting/main.dart';
import 'package:pc/Page/Other/ShowPicture/main.dart';
import 'package:pc/Util/FileUtils.dart';
import 'package:pc/main++.dart';

enum WindowType {
  UnKnown(rawValue: null),
  ShowImage(rawValue: "ShowImage"),
  Setting(rawValue: "Setting"),
  ;

  final String? rawValue;

  const WindowType({required this.rawValue});

  static WindowType from(String? rawValue) => values.firstWhere((x) => x.rawValue == rawValue, orElse: () => WindowType.UnKnown);
}

List<WindowController> _controllers = [];

void filterWindows(List<String> args) {
  String windowId = args[1];
  Map<String, dynamic> map = json.decode(args[2]);
  Map<String, dynamic>? params = map["params"];
  switch (WindowType.from(map["type"])) {
    case WindowType.ShowImage:
      List<String> images = params!["images"].map<String>((e) => e.toString()).toList();
      int index = params["index"] ?? 0;
      openPage(ShowPicturePage(pictures: images, index: index));
      break;
    case WindowType.Setting:
      openPage(SettingPage());
      break;
    default:
      break;
  }
}

Future<void> openWindow(WindowType type, {Map<String, dynamic>? params, Size? size, bool clearSubWindows = true}) async {
  if (clearSubWindows) {
    for (var i = _controllers.length - 1; i >= 0; i--) {
      _controllers.removeAt(i).close();
    }
  }
  final controller = await DesktopMultiWindow.createWindow(jsonEncode({
    "type": type.rawValue,
    "params": params,
  }));
  controller
    ..setFrame(const Offset(0, 0) & (size ?? const Size(860, 600)))
    ..center()
    ..show();
  _controllers.add(controller);
}

void setWindowMethodHandler() {
  DesktopMultiWindow.setMethodHandler((call, fromWindowId) async {
    final arguments = call.arguments;
    switch (call.method) {
      case "saveFile":
        String url = arguments["url"];
        await File(
          "${(await FileUtils.getDir(FileDir.download))}${DateTime.now().millisecondsSinceEpoch}_${url.split("/").last}",
        ).writeAsBytes(
          await readBytes(Uri.parse(url)),
        );
        return null;
      case "getCacheSize":
        return await FileUtils.getCacheSize();
      case "clearCache":
        await FileUtils.clearCache();
        return null;
    }
    return null;
  });
}
